#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Author          : ricsy
@File            : core.py
@Create Time     : 2025/6/18 05:30
@Last Modified   :
@Description     :
"""
import os
import sys

from theme_customizer.base import BaseCustomizer


class CoreManager(BaseCustomizer):
    """所有定制化功能的基类"""

    def apply(self):
        """应用所有定制化功能"""
        self.logger.info(f"当前语言：{self.app.config.language}", 2)
        self.logger.info(f"翻译目录：{self.app.config.locale_dirs}", 2)
        self.dump_all_templates()

    def dump_all_templates(self):
        """递归打印所有模板文件路径"""
        # 检查 Jinja2 环境中的路径
        if hasattr(self.app.builder.templates, "environment"):
            loader = self.app.builder.templates.environment.loader

            # 打印加载器类型
            self.logger.info(
                f"加载器类型: {type(loader).__module__}.{type(loader).__name__}", 2
            )

            # 获取所有模板路径（兼容多种加载器）
            template_paths = set()

            if hasattr(loader, "searchpath"):
                template_paths.update(loader.searchpath)
            elif hasattr(loader, "loaders"):
                for subloader in loader.loaders:
                    if hasattr(subloader, "searchpath"):
                        template_paths.update(subloader.searchpath)

                # 标准化路径并分类
                project_path = os.path.normpath(self.app.srcdir)  # 项目根目录
                system_path = os.path.normpath(sys.prefix)  # Python 解释器路径

                local_paths = []
                theme_paths = []
                system_paths = []

                for path in {os.path.normpath(p) for p in template_paths}:
                    # 判断项目本地模板（在项目目录内且不在 Python 解释器路径中）
                    if path.startswith(project_path) and system_path not in path:
                        local_paths.append(path)
                    # 判断主题模板（包含 _theme 字样且来自 Python 解释器路径）
                    elif "_theme" in path.lower() and system_path in path:
                        theme_paths.append(path)
                    # 系统基础模板
                    else:
                        system_paths.append(path)

                # 打印结果
                local_paths_str = "\n".join(list(sorted(local_paths)))
                self.logger.info(f"项目本地模板:\n{local_paths_str}", 2)

                theme_paths_str = "\n".join(list(sorted(theme_paths)))
                self.logger.info(f"主题模板:\n{theme_paths_str}", 2)

                system_paths_str = "\n".join(list(sorted(system_paths)))
                self.logger.info(f"系统基础模板:\n{system_paths_str}", 2)
